import cv2 as cv
import numpy as np

filePath = '../test_datas/numberOne.png'
img = cv.imread(filePath)
imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

thresh, maxValue = 127, 255
threshType = cv.THRESH_BINARY_INV
ret, thresh = cv.threshold(imgGray, thresh, maxValue, threshType)

retrievalMode = cv.RETR_TREE
approxMethod = cv.CHAIN_APPROX_NONE
contours, hierachy = cv.findContours(thresh, retrievalMode, approxMethod)

oneIdx = 0
cnt = contours[oneIdx]
x,y,w,h = cv.boundingRect(cnt)
center,size,angle = cv.minAreaRect(cnt)

imgBackGround = np.zeros(img.shape, np.uint8)
cv.drawContours(imgBackGround, contours, oneIdx, (255,255,255), -1)

box = cv.boxPoints((center,size,angle))
box = np.int0(box)
cv.drawContours(imgBackGround,[box],0,(0,0,255),1)

imgNew = np.zeros(img.shape, np.uint8)
cv.drawContours(imgNew, contours, oneIdx, (255,255,255), -1)
cv.drawContours(imgNew, [box],0, (0,255,0),1)

M = cv.getRotationMatrix2D(center, angle, scale=1)
dst = cv.warpAffine(imgNew, M, (img.shape[1],img.shape[0]))

cv.imshow("thresh", thresh)
cv.imshow("img", img)
cv.imshow("imgBG", imgBackGround)
cv.imshow("dst", dst)
cv.waitKey(0)
cv.destroyAllWindows()